package com.senyint.sys.utils.net.socket;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * {@code SocketServer}Socket服务端类<br>
 * 带线程池的服务端处理socket连接
 * <p>
 * 
 * @author WangNaiFei, WangNaiFei@senyint.com
 * @date 2017年1月18日 下午4:09:05
 * @version 1.0
 * @since jdk1.7+
 */
public class SocketServer {

	private static final Logger log = LoggerFactory.getLogger(SocketServer.class);
	/**
	 * server端口
	 */
	private static final int SERVER_PORT = 10000;
	private int port = SERVER_PORT;

	public void setPort(int port) {
		this.port = port;
	}

	/**
	 * 读取客户端消息休息时间 毫秒
	 */
	// private static final int SERVER_REFRESHINTERVAL = 500;
	// private int clientRefreshInterval = SERVER_REFRESHINTERVAL;
	// public void setClientRefreshInterval(int clientRefreshInterval) {
	// this.clientRefreshInterval = clientRefreshInterval;
	// }

	/**
	 * server
	 */
	private ServerSocket serverSocket;
	/**
	 * 线程池
	 */
	private ExecutorService pool;
	/**
	 * 处理对象
	 */
	private SocketServerRunnable runnable;

	public SocketServer(SocketServerRunnable runnable) throws IOException {
		if (runnable == null) {
			throw new RuntimeException("处理对象SocketServerRunnable不能为空");
		}
		this.runnable = runnable;

		serverSocket = new ServerSocket(port, 10);
		log.debug("创建ServerSocket，port：{}", port);
		final AtomicInteger count = new AtomicInteger(0);
		pool = Executors.newCachedThreadPool(new ThreadFactory() {
			public Thread newThread(Runnable r) {
				Thread thread = new Thread(r, "ThreadPool-new-" + count.incrementAndGet());
				log.debug("创建池中线程{}", thread.getName());
				return thread;
			}
		});

	}

	/**
	 * 服务端启动
	 * <p>
	 * 
	 * @author WangNaiFei, WangNaiFei@senyint.com
	 * @date 2017年1月18日 下午4:11:23
	 * @version 1.0
	 */
	public void start() {
		while (true) {
			try {
				Socket clientSocket = serverSocket.accept();
				log.debug("读取到客户端连接");
				runnable.setClientSocket(clientSocket);
				log.debug("线程执行");
				pool.execute(runnable);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		// SocketAddress sadd = new InetSocketAddress("127.0.0.1", 1300);
		// NioSocketConnector ioConnector = new NioSocketConnector();
		// ioConnector.setHandler(new HL7MessageHandler());
		// Map<String, IoFilter> m = new LinkedHashMap<String, IoFilter>();
		// DefaultIoFilterChainBuilder name = new DefaultIoFilterChainBuilder();
		// ProtocolCodecFilter filter = new ProtocolCodecFilter(new HL7Encoder(), new HL7Decoder());
		// m.put("codec", filter);
		// name.setFilters(m);
		// ioConnector.setFilterChainBuilder(name);
		// logger.debug("准备socket连接");
		// ConnectFuture conFuture = ioConnector.connect(sadd);
		// conFuture.awaitUninterruptibly();
		// logger.debug("准备socket连接session");
		// IoSession session = conFuture.getSession();
		// logger.debug("设置消息可读");
		// session.getConfig().setUseReadOperation(true);
		// logger.debug("获取byte消息");
		// byte[] bytes = "MSH|^~\\&|BS-ICSC|EHR|BSRIS|wj01|20150727053232|5831|ACK|16451|P|2.4 MSA||16451\r".toString().getBytes();
		// logger.debug("发送socket消息");
		// session.write(bytes).awaitUninterruptibly();
		// logger.debug("准备接收socket返回消息");
		// ReadFuture resp = session.read();
		// if (resp.awaitUninterruptibly(20, TimeUnit.SECONDS)) {
		// logger.debug("开始接收socket返回消息");
		// Object respMsg = resp.getMessage();
		// logger.debug("socket消息：" + respMsg);f
		// }
		// session.close(true);
	}
}